import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, InputNumber, Space, Tag, Modal, message, Descriptions, Popconfirm, Switch, DatePicker, Select, Badge } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, FireOutlined, SearchOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

// 获取充值套餐列表
const fetchPackages = async (params) => {
  return request('/api/v1/recharge/package', {
    method: 'GET',
    params,
  });
};

// 获取充值套餐详情
const fetchPackageDetail = async (id) => {
  return request(`/api/v1/recharge/package/${id}`, {
    method: 'GET',
  });
};

// 创建充值套餐
const createPackage = async (data) => {
  return request('/api/v1/recharge/package', {
    method: 'POST',
    data,
  });
};

// 更新充值套餐
const updatePackage = async (id, data) => {
  return request(`/api/v1/recharge/package/${id}`, {
    method: 'PUT',
    data,
  });
};

// 删除充值套餐
const deletePackage = async (id) => {
  return request(`/api/v1/recharge/package/${id}`, {
    method: 'DELETE',
  });
};

const RechargePackage = () => {
  const [packages, setPackages] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [packageForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchParams, setSearchParams] = useState({});
  const [detailVisible, setDetailVisible] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [currentPackage, setCurrentPackage] = useState(null);
  const [formTitle, setFormTitle] = useState('创建充值套餐');
  const [stores, setStores] = useState([]);
  const [isEdit, setIsEdit] = useState(false);

  // 获取充值套餐列表
  const fetchPackageList = async () => {
    try {
      setLoading(true);
      const res = await fetchPackages({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      });
      if (res.success) {
        setPackages(res.data.list || []);
        setPagination({
          ...pagination,
          total: res.data.total,
        });
      } else {
        message.error(res.message || '获取充值套餐列表失败');
      }
    } catch (error) {
      console.error('获取充值套餐列表出错:', error);
      message.error('获取充值套餐列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取门店列表
  const fetchStores = async () => {
    try {
      const res = await request('/api/v1/store', {
        method: 'GET',
      });
      if (res.success) {
        setStores(res.data.list || []);
      } else {
        message.error(res.message || '获取门店列表失败');
      }
    } catch (error) {
      console.error('获取门店列表出错:', error);
      message.error('获取门店列表失败');
    }
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '套餐名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '套餐类型',
      dataIndex: 'type',
      key: 'type',
      render: (type) => (
        <Tag color={type === 1 ? 'blue' : 'green'}>
          {type === 1 ? '全国通用' : '单门店'}
        </Tag>
      ),
    },
    {
      title: '适用门店',
      dataIndex: 'store_name',
      key: 'store_name',
      render: (text, record) => {
        return record.type === 2 ? (stores.find(store => store.id === record.store_id)?.name || '-') : '全部门店';
      },
    },
    {
      title: '充值金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '赠送金额',
      dataIndex: 'gift_amount',
      key: 'gift_amount',
      render: (gift_amount) => `¥${(gift_amount || 0).toFixed(2)}`,
    },
    {
      title: '赠送积分',
      dataIndex: 'gift_points',
      key: 'gift_points',
      render: (points) => points || 0,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Badge 
          status={status === 1 ? 'success' : 'error'} 
          text={status === 1 ? '启用' : '禁用'} 
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_, record) => (
        <Space size="small">
          <Button type="link" size="small" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此充值套餐吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" size="small" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理表格变化
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination(pagination);
  };

  useEffect(() => {
    fetchPackageList();
    fetchStores();
  }, [pagination.current, pagination.pageSize, searchParams]);

  // 处理添加套餐
  const handleAdd = () => {
    setIsEdit(false);
    setCurrentPackage(null);
    setFormTitle('创建充值套餐');
    
    packageForm.setFieldsValue({
      name: '',
      description: '',
      amount: 0,
      gift_amount: 0,
      gift_points: 0,
      status: true,
      type: 1,
    });
    
    setFormVisible(true);
  };

  // 处理编辑套餐
  const handleEdit = (record) => {
    setIsEdit(true);
    setCurrentPackage(record);
    setFormTitle('编辑充值套餐');
    
    packageForm.setFieldsValue({
      name: record.name,
      description: record.description,
      amount: record.amount,
      gift_amount: record.gift_amount,
      gift_points: record.gift_points,
      status: record.status === 1,
      type: record.type || 1,
      store_id: record.store_id,
    });
    
    setFormVisible(true);
  };

  // 处理查看套餐详情
  const handleViewDetail = async (record) => {
    try {
      setLoading(true);
      const res = await fetchPackageDetail(record.id);
      if (res.success) {
        setCurrentPackage(res.data);
        setDetailVisible(true);
      } else {
        message.error(res.message || '获取充值套餐详情失败');
      }
    } catch (error) {
      console.error('获取充值套餐详情出错:', error);
      message.error('获取充值套餐详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理删除套餐
  const handleDelete = async (id) => {
    try {
      setLoading(true);
      const res = await request(`/api/v1/recharge/package/${id}`, {
        method: 'DELETE',
      });
      
      if (res.success) {
        message.success('删除套餐成功');
        fetchPackageList();
      } else {
        message.error(res.message || '删除套餐失败');
      }
    } catch (error) {
      console.error('删除套餐出错:', error);
      message.error('删除套餐失败');
    } finally {
      setLoading(false);
    }
  };

  // 创建/编辑表单提交
  const handleFormSubmit = async () => {
    try {
      const values = await packageForm.validateFields();
      const type = parseInt(values.type, 10);
      
      // 先检查类型为单门店但没有选择门店的情况
      if (type === 2 && (!values.store_id || values.store_id <= 0)) {
        message.error('请选择适用门店');
        return;
      }
      
      const submitData = {
        ...values,
        status: values.status ? 1 : 0,
        amount: parseFloat(values.amount),
        gift_amount: parseFloat(values.gift_amount || 0),
        gift_points: parseInt(values.gift_points || 0, 10),
        type: type,
      };
      
      // 如果是全国通用类型，移除store_id字段
      if (submitData.type === 1) {
        delete submitData.store_id;
      }

      const url = isEdit
        ? `/api/v1/recharge/package/${currentPackage.id}`
        : '/api/v1/recharge/package';
      
      const method = isEdit ? 'PUT' : 'POST';
      
      const res = await request(url, {
        method,
        data: submitData,
      });
      
      if (res.success) {
        message.success(isEdit ? '更新成功' : '创建成功');
        setFormVisible(false);
        fetchPackageList();
      } else {
        message.error(res.message || (isEdit ? '更新失败' : '创建失败'));
      }
    } catch (error) {
      console.error('表单提交出错:', error);
    }
  };

  // 处理搜索
  const handleSearch = (values) => {
    const params = {};
    if (values.name) {
      params.name = values.name;
    }
    if (values.type) {
      params.type = values.type;
    }
    if (values.status !== undefined) {
      params.status = values.status;
    }
    if (values.is_hot !== undefined) {
      params.is_hot = values.is_hot;
    }
    
    setSearchParams(params);
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 处理重置
  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  return (
    <PageContainer title="充值套餐配置">
      <Card>
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 24 }}
        >
          <Form.Item name="name" label="套餐名称">
            <Input placeholder="请输入套餐名称" allowClear />
          </Form.Item>
          <Form.Item name="type" label="套餐类型">
            <Select placeholder="请选择类型" allowClear style={{ width: 120 }}>
              <Select.Option value={1}>全国通用</Select.Option>
              <Select.Option value={2}>单门店</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" allowClear style={{ width: 120 }}>
              <Select.Option value={1}>启用</Select.Option>
              <Select.Option value={0}>禁用</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="is_hot" label="是否热门">
            <Select placeholder="请选择" allowClear style={{ width: 120 }}>
              <Select.Option value={1}>热门</Select.Option>
              <Select.Option value={0}>普通</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                <SearchOutlined /> 搜索
              </Button>
              <Button onClick={handleReset}>重置</Button>
              <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                添加套餐
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
          columns={columns}
          dataSource={packages}
          rowKey="id"
          pagination={pagination}
          loading={loading}
          onChange={(pagination) => setPagination(pagination)}
        />

        {/* 套餐详情弹窗 */}
        <Modal
          title="套餐详情"
          visible={detailVisible}
          onCancel={() => setDetailVisible(false)}
          footer={[
            <Button key="close" onClick={() => setDetailVisible(false)}>
              关闭
            </Button>,
          ]}
          width={700}
        >
          {currentPackage && (
            <Descriptions bordered column={2}>
              <Descriptions.Item label="套餐名称">{currentPackage.name}</Descriptions.Item>
              <Descriptions.Item label="充值金额">¥{(currentPackage.amount / 100).toFixed(2)}</Descriptions.Item>
              <Descriptions.Item label="赠送金额">¥{(currentPackage.gift_amount / 100).toFixed(2)}</Descriptions.Item>
              <Descriptions.Item label="折扣">{currentPackage.discount === 100 ? '无折扣' : `${currentPackage.discount / 10}折`}</Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={currentPackage.status === 1 ? 'green' : 'red'}>
                  {currentPackage.status === 1 ? '启用' : '禁用'}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">{currentPackage.createdAt}</Descriptions.Item>
              <Descriptions.Item label="描述" span={2}>{currentPackage.description || '-'}</Descriptions.Item>
            </Descriptions>
          )}
        </Modal>

        {/* 创建/编辑套餐弹窗 */}
        <Modal
          title={formTitle}
          visible={formVisible}
          onCancel={() => setFormVisible(false)}
          footer={[
            <Button key="back" onClick={() => setFormVisible(false)}>
              取消
            </Button>,
            <Button key="submit" type="primary" onClick={handleFormSubmit}>
              确定
            </Button>,
          ]}
          width={600}
          destroyOnClose
        >
          <Form
            form={packageForm}
            layout="vertical"
          >
            <Form.Item
              name="name"
              label="套餐名称"
              rules={[{ required: true, message: '请输入套餐名称' }]}
            >
              <Input placeholder="请输入套餐名称" />
            </Form.Item>

            <Form.Item
              name="type"
              label="套餐类型"
              rules={[{ required: true, message: '请选择套餐类型' }]}
            >
              <Select 
                placeholder="请选择套餐类型"
                onChange={(value) => {
                  if (value === 1) {
                    packageForm.setFieldsValue({ store_id: undefined });
                  }
                }}
              >
                <Select.Option value={1}>全国通用</Select.Option>
                <Select.Option value={2}>单门店</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}
            >
              {({ getFieldValue }) => 
                getFieldValue('type') === 2 ? (
                  <Form.Item
                    name="store_id"
                    label="适用门店"
                    rules={[{ required: true, message: '请选择适用门店' }]}
                  >
                    <Select placeholder="请选择门店">
                      {stores.map(store => (
                        <Select.Option key={store.id} value={store.id}>{store.name}</Select.Option>
                      ))}
                    </Select>
                  </Form.Item>
                ) : null
              }
            </Form.Item>

            <Form.Item
              name="amount"
              label="充值金额(元)"
              rules={[{ required: true, message: '请输入充值金额' }]}
            >
              <InputNumber
                min={0}
                precision={2}
                style={{ width: '100%' }}
                placeholder="请输入充值金额"
              />
            </Form.Item>

            <Form.Item
              name="gift_amount"
              label="赠送金额(元)"
              rules={[{ required: true, message: '请输入赠送金额' }]}
            >
              <InputNumber
                min={0}
                precision={2}
                style={{ width: '100%' }}
                placeholder="请输入赠送金额"
              />
            </Form.Item>

            <Form.Item
              name="gift_points"
              label="赠送积分"
            >
              <InputNumber
                min={0}
                style={{ width: '100%' }}
                placeholder="请输入赠送积分"
              />
            </Form.Item>

            <Form.Item
              name="description"
              label="套餐描述"
            >
              <Input.TextArea rows={4} placeholder="请输入套餐描述" />
            </Form.Item>

            <Form.Item
              name="status"
              label="状态"
              valuePropName="checked"
            >
              <Switch checkedChildren="启用" unCheckedChildren="禁用" />
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </PageContainer>
  );
};

export default RechargePackage;